local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local scoreValue
local totalScoreValue
local levelText
local endLevelAudio = audio.loadSound("endlevel.wav")
local levelAudioChannel

----------------------------------------------------------------------------------
-- 
--      NOTE:
--      
--      Code outside of listener functions (below) will only be executed once,
--      unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------


-- local forward references should go here --


---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene(sceneEvent)
        local group = self.view
		
        -----------------------------------------------------------------------------

        --      CREATE display objects and add them to 'group' here.
        --      Example use-case: Restore 'group' from previously saved state.

        -----------------------------------------------------------------------------
		print("createScene")
		
		background = display.newRect(0,0,display.contentWidth,display.contentHeight)
		background:setFillColor(42,127,255)
		
		levelText = display.newText("Level Cleared",display.contentWidth/2,0,native.systemFont,30)
		--levelText:scale(5,5)
		levelText:setTextColor(255,255,255)
		levelText.x = display.contentWidth/2
		levelText.y = 40
		
		scoreValue = display.newText("99999",display.contentWidth/2-80,140,native.systemFont,30)
		scoreValue:setTextColor(255,255,255)
		scoreValue.x = display.contentWidth/2 + 80	
		scoreValue.y = display.contentHeight/2 - 25
		--scoreValue.text = sceneEvent.params.totalScore
		
		totalScoreValue = display.newText("99999",display.contentWidth/2-80,140,native.systemFont,30)
		totalScoreValue:setTextColor(255,255,255)
		totalScoreValue.x = display.contentWidth/2 + 80	
		totalScoreValue.y = display.contentHeight/2 - 120
		
		
		
		
		--local background = display.newRect(0,0,display.contentWidth,display.contentHeight)
		--background:setFillColor(255,255,255)

		--local endLevelBG = display.newImage("endLevelBg.png")
	
		local nextButtonUp = display.newImageRect("leNextBntUp.png",79,77)
		local nextButtonDown = display.newImageRect("leNextBntDown.png",79,76)
		local menuLvButtonUp = display.newImageRect("leMenuBntUp.png",79,77)
		local menuLvButtonDown = display.newImageRect("leMenuBntDown.png",79,77)
		local reloadButtonUp = display.newImageRect("leReloadBntUp.png",79,75)
		local reloadButtonDown = display.newImageRect("leReloadBntDown.png",79,76)
		
		local levelScoreBG = display.newImageRect("endlevelScoreBG.png",294,78)
		local totalScoreBG = display.newImageRect("levelTotal.png",294,78)
		
		
		
		local postHighScoreButtonUp = display.newImageRect("postHighScoreBntUp.png",279,84)
		local postHighScoreButtonDown = display.newImageRect("postHighScoreBntDown.png",279,77)
		
		--endLevelBG.x = display.contentWidth/2
		--endLevelBG.y = display.contentHeight/2
	
		totalScoreBG.x = display.contentWidth/2
		totalScoreBG.y = 130
		
		levelScoreBG.x = display.contentWidth/2
		levelScoreBG.y = 220

		postHighScoreButtonDown.isVisible = false
		
		postHighScoreButtonUp.x = display.contentWidth/2
		postHighScoreButtonUp.y = display.contentHeight/2 + 80
		postHighScoreButtonDown.x = display.contentWidth/2
		postHighScoreButtonDown.y = display.contentHeight/2 + 80
		--postHighScoreButtonUp:scale(0.7,0.7)
		--postHighScoreButtonDown:scale(0.8,0.8)
		
		reloadButtonDown.isVisible = false
		reloadButtonUp.x = display.contentWidth/2 - 100
		reloadButtonUp.y = display.contentHeight/2 + 180
		reloadButtonDown.x = display.contentWidth/2 - 100
		reloadButtonDown.y = display.contentHeight/2 + 180
		--reloadButtonDown:scale(1.1,1.1)
		
		menuLvButtonDown.isVisible = false
		menuLvButtonUp.x = display.contentWidth/2
		menuLvButtonUp.y = display.contentHeight/2 + 180
		menuLvButtonDown.x = display.contentWidth/2
		menuLvButtonDown.y = display.contentHeight/2 + 180
		--menuLvButtonDown:scale(1.1,1.1)
		
		nextButtonDown.isVisible = false
		nextButtonUp.x = display.contentWidth/2 + 100
		nextButtonUp.y = display.contentHeight/2 + 180
		nextButtonDown.x = display.contentWidth/2 + 100
		nextButtonDown.y = display.contentHeight/2 + 180
		--nextButtonDown:scale(1.1,1.1)
		
		group:insert(background)
		group:insert(totalScoreBG)
		--group:insert(endLevelBG)
		group:insert(levelScoreBG)
		group:insert(nextButtonUp)
		group:insert(nextButtonDown)
		group:insert(menuLvButtonUp)
		group:insert(menuLvButtonDown)
		group:insert(reloadButtonUp)
		group:insert(reloadButtonDown)
		group:insert(levelText)
		group:insert(scoreValue)
		group:insert(totalScoreValue)
		group:insert(postHighScoreButtonUp)
		group:insert(postHighScoreButtonDown)

		local function nextBntTouch(touchEvent) 						
			local function gotoNext()
				print("Goto Next")
				global_levelNumber = global_levelNumber + 1
				storyboard.purgeScene("GamePlay")				
				storyboard.gotoScene("GamePlay",{time=200,effect="fade"})
			end						
			if (touchEvent.phase == "began") then
				nextButtonDown.isVisible = true
			else
				gotoNext()
				nextButtonDown.isVisible = false
			end			
			return true
		end 
		nextButtonUp:addEventListener( "touch", nextBntTouch )
		
		local function menuBntTouch(touchEvent)
			local function menuGame()
				print("goto menu")
				storyboard.purgeScene("EndLevelPopup")
				storyboard.gotoScene("Menu",{time=200,effect="fade"})												
			end						
			if (touchEvent.phase == "began") then
				menuLvButtonDown.isVisible = true
			else
				menuGame()
				menuLvButtonDown.isVisible = false
			end			
			return true
		end 
		menuLvButtonUp:addEventListener( "touch", menuBntTouch )
			
		local function reloadBntTouch(touchEvent)
			local function reloadGame()
				print("Reload")				
				storyboard.purgeScene("EndLevelPopup")
				storyboard.gotoScene("GamePlay",{time=500,effect="zoomInOut" })
								
			end						
			if (touchEvent.phase == "began") then
				reloadButtonDown.isVisible = true
			else
				reloadGame()
				reloadButtonDown.isVisible = false
			end			
			return true
		end 
		reloadButtonUp:addEventListener( "touch", reloadBntTouch )
		
		
		local function highScoreBntTouch(event) 			
			local function setHighScore()
				
				print("Submit Score Facebook")
				
				postHighScoreButtonDown.isVisible = false
				postHighScoreButtonUp.isVisible = true
				
				local gameFacebook = require "GameFacebook"
				local persistence = require "Persistence"
				
				local highscore = 0
				
				for contLevel=1,global_levelNumber do
					highscore = highscore + tonumber(persistence.loadValue(HIGH_SCORE_SAVE_FILE..contLevel))
				end
				gameFacebook.postHighScore(highscore)
				
			end			
			if (event.phase == "began") then
				postHighScoreButtonDown.isVisible = true
				postHighScoreButtonUp.isVisible = false
				timer.performWithDelay(100,setHighScore,1)
			end						
			return true
		end 
		postHighScoreButtonUp:addEventListener( "touch", highScoreBntTouch )
		
		
	
end


-- Called BEFORE scene has moved onscreen:
function scene:willEnterScene( event )
		local group = self.view
		local levelPreviousScore = 0
		local persistence = require "Persistence" 
		
		if ( levelText ~= nil ) then
			levelText.text = "Level "..global_levelNumber .." Cleared"
		end
		
		print("willEnterScene "..event.params.totalScore)
		
		
		
		
		levelPreviousScore = tonumber(persistence.loadValue(HIGH_SCORE_SAVE_FILE..global_levelNumber))
		
		print("Previous score "..levelPreviousScore)
		
		if ( levelPreviousScore < event.params.totalScore ) then		
			print("Save Value key ".. HIGH_SCORE_SAVE_FILE..global_levelNumber)
			persistence.saveValue(HIGH_SCORE_SAVE_FILE..global_levelNumber,event.params.totalScore)
		else
			event.params.totalScore = levelPreviousScore 	
		end
			
		
		
		print("save level "..global_levelNumber + 1)
		persistence.saveValue(LEVEL_SAVE_FILE,global_levelNumber+1)
		
		if ( scoreValue ~= nil) then
			scoreValue.text = event.params.totalScore
		end
	
		local highscore = event.params.totalScore
				
		for contLevel=1,global_levelNumber do
			highscore = highscore + tonumber(persistence.loadValue(HIGH_SCORE_SAVE_FILE..contLevel-1))
		end	
		
		
		if ( totalScoreValue ~= nil ) then
			totalScoreValue.text = highscore
		end
			
        -----------------------------------------------------------------------------

        --      This event requires build 2012.782 or later.

        -----------------------------------------------------------------------------

end


-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
        local group = self.view
		print("enterScene")
		levelAudioChannel = audio.play(endLevelAudio)
        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. start timers, load audio, start listeners, etc.)

        -----------------------------------------------------------------------------
		storyboard.purgeScene("GamePlay")
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
        local group = self.view
        audio.stop(levelAudioChannel)

        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)

        -----------------------------------------------------------------------------

end


-- Called AFTER scene has finished moving offscreen:
function scene:didExitScene( event )
        local group = self.view

        -----------------------------------------------------------------------------

        --      This event requires build 2012.782 or later.

        -----------------------------------------------------------------------------

end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
        local group = self.view

        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. remove listeners, widgets, save state, etc.)

        -----------------------------------------------------------------------------

end


-- Called if/when overlay scene is displayed via storyboard.showOverlay()
function scene:overlayBegan( event )
        local group = self.view
        local overlay_name = event.sceneName  -- name of the overlay scene

        -----------------------------------------------------------------------------

        --      This event requires build 2012.797 or later.

        -----------------------------------------------------------------------------

end


-- Called if/when overlay scene is hidden/removed via storyboard.hideOverlay()
function scene:overlayEnded( event )
        local group = self.view
        local overlay_name = event.sceneName  -- name of the overlay scene

        -----------------------------------------------------------------------------

        --      This event requires build 2012.797 or later.

        -----------------------------------------------------------------------------

end



---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "willEnterScene" event is dispatched before scene transition begins
scene:addEventListener( "willEnterScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "didExitScene" event is dispatched after scene has finished transitioning out
scene:addEventListener( "didExitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

-- "overlayBegan" event is dispatched when an overlay scene is shown
scene:addEventListener( "overlayBegan", scene )

-- "overlayEnded" event is dispatched when an overlay scene is hidden/removed
scene:addEventListener( "overlayEnded", scene )

---------------------------------------------------------------------------------

return scene